import router from '@/router';
import store from '@/store';
import axios from 'axios';
import { getToken } from './auth';

// create an axios instance
const service = axios.create({
  // const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['authorization'] = getToken();
    }
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

const ILLEGAL_REQUEST = 30100;
const ILLEGAL_TOKEN = 30101;
const TOKEN_EXPIRED = 30102;
const LOGIN_EXPIRED_ALERT = '您的登录已失效, 请重新登录';
const LoginExpired = { status: TOKEN_EXPIRED, error: LOGIN_EXPIRED_ALERT, message: LOGIN_EXPIRED_ALERT, data: null };

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   * @param {*} response
   * @return {Promise<AxiosResponse<any>>}
   */
  response => {
    if (response.status === 401) {
      // router.push(`/login`);
      store.dispatch('user/resetToken');
      router.push('/login');
      response.data = LoginExpired;
      return response;
    }
    const res = response.data;
    if (res) {
      if (res.status === ILLEGAL_REQUEST || res.status === ILLEGAL_TOKEN || res.status === TOKEN_EXPIRED) {
        store.dispatch('user/resetToken');
        router.push('/login');
        response.data = LoginExpired;
        return response;
      }
    }
    return response;
  },
  error => {
    if (error.status === 401) {
      store.dispatch('user/resetToken');
      router.push('/login');
    }
    return Promise.reject(error);
  }
);

export default service;
